package client;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.*;

import message.DataMessage;

public class Client {
	
	static String serverHost = "";
	
	public static String localAddr = "";
	
	public static String getServerAddr(String localAdd){
		String[] x = localAdd.split("\\.");
		String server = "";
		server += x[0] + '.' + x[1] + '.' + x[2] + '.';
		int lastOctet = Integer.parseInt(x[3]);
		server += lastOctet - lastOctet%10;
//		System.out.println("server: " + server);
		return server;
	}
	
	public static void main(String argv[]) throws Exception {
		
		BufferedReader inFromUser = 
			new BufferedReader(new InputStreamReader(System.in));
				
		try {
		    InetAddress addr = InetAddress.getLocalHost();

		    // Get IP Address
		    System.out.println("local IP address: " + addr.getHostAddress());
		    
//		    serverHost = getServerAddr(addr.getHostAddress());
		    
//		    serverHost = "127.0.0.1"; //pour tester
		    serverHost = "192.168.0.24"; //pour tester
//		    localAddr = "192.168.56.112"; //pour tester
		    localAddr = addr.getHostAddress();
			
		    // create socket to dedicated server
		    Socket clientSocket;		

		    System.out.println("Creating Socket with server " + serverHost);
		    
			clientSocket = new Socket(serverHost, 1026);
			
			ClientReceiveThread rt = new ClientReceiveThread(clientSocket);
			rt.start();
			
			System.out.println("Socket with server " + serverHost + " created!");
			
			DataOutputStream outToServer = 
				new DataOutputStream(clientSocket.getOutputStream());
			
			BufferedReader inFromServer = 
				new BufferedReader(new
						InputStreamReader(clientSocket.getInputStream()));
			
			String sentence = "req_INIT";			
			outToServer.writeBytes(sentence + '\n');			
			
			System.out.println("Request info of which host? ");
			
			String req = "req_" + inFromUser.readLine() + "_" + localAddr;
			
			outToServer.writeBytes(req + '\n');
			
			/*
			int i = 0;
			while(true){
				String serverMsg = inFromServer.readLine();
				if(serverMsg != null){
					System.out.println("FROM SERVER: " + serverMsg);
					
					if(DataMessage.getDestAddress(serverMsg).equals(localAddr)){
						//reply to srcAddr
						String reply = "req_" + DataMessage.getSrcAddress(serverMsg) + "_" + localAddr;
						outToServer.writeBytes(reply + '\n');
					}
					else{
						//do nothing
					}
				}
				i++;
			}						
					
			sentence = "req_STOP";			
			outToServer.writeBytes(sentence);
				
			clientSocket.close();*/
		}
		catch (UnknownHostException ex) {
			System.err.println("No service at host " + ex);			
		}
	}
}
